package com.amt.olcacon.utils;

import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;

import java.io.*;
import java.math.BigInteger;
import java.util.List;

public class TablePlaceholderReplacerUtil {
    
    /**
     * 替换文档中的表格占位符为实际表格
     * 
     * @param doc 文档对象
     * @param placeholder 占位符名称（如"{{ALLOCATION_TABLE}}"）
     * @param headers 表头数组
     * @param dataRows 数据行列表，每个元素是一个字符串数组，代表一行数据
     * @return 是否替换成功
     */
    public static boolean replaceTablePlaceholder(XWPFDocument doc, String placeholder, 
                                                 String[] headers, List<String[]> dataRows) {
        // 遍历所有表格
        for (XWPFTable table : doc.getTables()) {
            // 检查每个单元格是否包含占位符
            for (XWPFTableRow row : table.getRows()) {
                for (XWPFTableCell cell : row.getTableCells()) {
                    if (containsPlaceholder(cell, placeholder)) {
                        // 替换这个表格的内容
                        replaceTableWithData(table, headers, dataRows);
                        return true;
                    }
                }
            }
        }
        return false;
    }

    /**
     * 创建表格
     * @param headers
     * @param rows
     * @return
     */
    public static void addTable(XWPFParagraph paragraph,XWPFDocument doc, String[] headers, List<String[]> rows) {
        // 创建表格
        XWPFTable table = doc.insertNewTbl(paragraph.getCTP().newCursor());
        XWPFTableRow headerRow = table.getRow(0);
        for (int i = 0; i < headers.length; i++) {
            if (i == 0) headerRow.getCell(0).setText(headers[i]);
            else headerRow.addNewTableCell().setText(headers[i]);
        }
        for (String[] row : rows) {
            XWPFTableRow tableRow = table.createRow();
            for (int i = 0; i < headers.length; i++) {
                tableRow.getCell(i).setText(row[i]);
            }
        }

    }


    public static String generateTableAsString(String[] headers, List<String[]> rows) {
        StringBuilder sb = new StringBuilder();

        // 表头
        for (String h : headers) {
            sb.append(h).append("\t");
        }
        sb.append("\n");

        // 内容
        for (String[] row : rows) {
            for (String cell : row) {
                sb.append(cell == null ? "" : cell).append("\t");
            }
            sb.append("\n");
        }

        return sb.toString();
    }
    public static void addTable(XWPFDocument doc, String[] headers, List<String[]> rows) {
        XWPFTable table = doc.createTable();
        XWPFTableRow headerRow = table.getRow(0);
        for (int i = 0; i < headers.length; i++) {
            if (i == 0) {
                headerRow.getCell(0).setText(headers[i]);
            } else {
                headerRow.addNewTableCell().setText(headers[i]);
            }
        }
        for (String[] row : rows) {
            XWPFTableRow tableRow = table.createRow();
            for (int i = 0; i < headers.length; i++) {
                tableRow.getCell(i).setText(row[i]);
            }
        }
    }

    /**
     * 检查单元格是否包含指定占位符
     */
    private static boolean containsPlaceholder(XWPFTableCell cell, String placeholder) {
        String cellText = getCellText(cell);
        return cellText != null && cellText.contains(placeholder);
    }
    
    /**
     * 获取单元格的完整文本
     */
    private static String getCellText(XWPFTableCell cell) {
        StringBuilder text = new StringBuilder();
        for (XWPFParagraph paragraph : cell.getParagraphs()) {
            if (paragraph.getText() != null) {
                text.append(paragraph.getText());
            }
        }
        return text.toString();
    }
    
    /**
     * 用实际数据替换表格内容
     */
    private static void replaceTableWithData(XWPFTable table, String[] headers, List<String[]> dataRows) {
        // 清空表格现有内容
        clearTable(table);
        
        // 创建表头
        createTableHeader(table, headers);
        
        // 添加数据行
        addDataRows(table, dataRows);
        
        // 设置表格样式
        setupTableStyle(table);
    }
    
    /**
     * 清空表格
     */
    private static void clearTable(XWPFTable table) {
        int rowCount = table.getNumberOfRows();
        for (int i = rowCount - 1; i >= 0; i--) {
            table.removeRow(i);
        }
    }
    
    /**
     * 创建表头
     */
    private static void createTableHeader(XWPFTable table, String[] headers) {
        XWPFTableRow headerRow = table.createRow();
        
        for (int i = 0; i < headers.length; i++) {
            XWPFTableCell cell = headerRow.getCell(i);
            if (cell == null) {
                cell = headerRow.createCell();
            }
            setHeaderCell(cell, headers[i]);
        }
    }
    
    /**
     * 设置表头单元格
     */
    private static void setHeaderCell(XWPFTableCell cell, String text) {
        // 清空单元格
        for (int i = cell.getParagraphs().size() - 1; i >= 0; i--) {
            cell.removeParagraph(i);
        }
        
        XWPFParagraph paragraph = cell.addParagraph();
        paragraph.setAlignment(ParagraphAlignment.CENTER);
        
        XWPFRun run = paragraph.createRun();
        run.setText(text);
        run.setBold(true);
        run.setFontSize(10);
        run.setFontFamily("宋体");
        
        cell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER);
    }
    
    /**
     * 添加数据行
     */
    private static void addDataRows(XWPFTable table, List<String[]> dataRows) {
        for (int i = 0; i < dataRows.size(); i++) {
            String[] rowData = dataRows.get(i);
            XWPFTableRow dataRow = table.createRow();
            
            for (int j = 0; j < rowData.length; j++) {
                XWPFTableCell cell = dataRow.getCell(j);
                if (cell == null) {
                    cell = dataRow.createCell();
                }
                // 判断是否为数字列（这里简单按列索引判断，你可根据需要调整）
                boolean centerAlign = (j == 0 || j == 4); // 序号和分配系数居中
                setDataCell(cell, rowData[j] != null ? rowData[j] : "", centerAlign);
            }
        }
    }
    
    /**
     * 设置数据单元格
     */
    private static void setDataCell(XWPFTableCell cell, String text, boolean centerAlign) {
        if (cell == null) return;
        
        // 清空单元格
        for (int i = cell.getParagraphs().size() - 1; i >= 0; i--) {
            cell.removeParagraph(i);
        }
        
        XWPFParagraph paragraph = cell.addParagraph();
        if (centerAlign) {
            paragraph.setAlignment(ParagraphAlignment.CENTER);
        } else {
            paragraph.setAlignment(ParagraphAlignment.LEFT);
        }
        
        XWPFRun run = paragraph.createRun();
        run.setText(text);
        run.setFontSize(9);
        run.setFontFamily("宋体");
        
        cell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER);
    }
    
    /**
     * 设置表格样式
     */
    private static void setupTableStyle(XWPFTable table) {
        try {
            CTTbl ctTable = table.getCTTbl();
            CTTblPr tblPr = ctTable.getTblPr();
            if (tblPr == null) {
                tblPr = ctTable.addNewTblPr();
            }
            
            // 表格宽度 - 根据窗口自动调整
            CTTblWidth tblWidth = tblPr.addNewTblW();
            tblWidth.setType(STTblWidth.AUTO);
            tblWidth.setW(BigInteger.valueOf(0));
            
            // 表格边框
            CTTblBorders borders = tblPr.addNewTblBorders();
            setBorder(borders.addNewTop(), STBorder.SINGLE, 4, "000000");
            setBorder(borders.addNewLeft(), STBorder.SINGLE, 4, "000000");
            setBorder(borders.addNewBottom(), STBorder.SINGLE, 4, "000000");
            setBorder(borders.addNewRight(), STBorder.SINGLE, 4, "000000");
            setBorder(borders.addNewInsideH(), STBorder.SINGLE, 2, "000000");
            setBorder(borders.addNewInsideV(), STBorder.SINGLE, 2, "000000");
            
        } catch (Exception e) {
            System.err.println("设置表格样式时出错: " + e.getMessage());
        }
    }
    
    /**
     * 设置边框样式
     */
    private static void setBorder(CTBorder border, STBorder.Enum style, int size, String color) {
        border.setVal(style);
        border.setSz(BigInteger.valueOf(size));
        border.setColor(color);
    }
}
